<?php

declare (strict_types = 1);
namespace app\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\Cache;
use think\Image;
use dh2y\qrcode\QRcode;
use app\controller\Token;


//Token管理类
class Imagex{
    var $access_token='';

    public function index(){

    }

    //取得微信登录token
    public function get_access_token(){
        $access_token = Cache::get('wx_qrcode_token');
        if(!empty($access_token)){
            return $access_token;
        }
        $appid  = "wx15d32cb44449c60f";
        $secret = "34d1ab0202953f1d537e7a147d12dcea";
        $api_url= "https://api.weixin.qq.com/cgi-bin/stable_token";//?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $data = json_encode(array('appid'=>$appid,'secret'=>$secret,'grant_type'=>'client_credential'));
        $access_token = json_decode($this->http_post($api_url,'',$data),true); 
        Cache::set('wx_qrcode_token',$access_token['access_token'],7100);
        return Cache::get('wx_qrcode_token');
    }

    //推广海报
    public function tg_image(){
        $all=Request::param();

        //一，检测用户，取得手机号
        if($_SERVER['SERVER_ADDR']=='127.0.0.1' || !empty($all['test'])){
            $customer =Db::table('customer')->find(1075);
        }else{
            if(empty($all['token'])) return json(['code'=>0,'msg'=>'请登录！']);
            $token =new token();
            $res = $token->check_token($all['token']);
            if($res['code']==0) return json($res);
            $customer = $res['customer']; 
        }
        
        $qr_file='upload/tg/qr_'.$customer['id'].'.png';                //二唯码文件及
        $qr_file_thumb='upload/tg/thumb_qr_'.$customer['id'].'.png';    //略缩图文件名
        $tg_file ='upload/tg/tg_'.$customer['id'].'.jpg';               //加水印的图片文件名

        //if(is_file($tg_file)) return json(['code'=>1,'url'=>$tg_file]); //推广海报存在就是直接返回

        $access_token = $this->get_access_token();
        $page = 'pagesB/register/register';

        //调用wx小程序码接口，产生二唯码，并写入到一个图片，然后压缩到合适的尺寸
        $qr_url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
        $data = json_encode(array('page'=>$page,'scene'=>$customer['mobile'],'width'=>280));
        $qr_wx = $this->http_post($qr_url,'',$data); 
        file_put_contents($qr_file,$qr_wx); //这是返回的二唯码二进制文件内容，需要写入一个文件。

        //return json(['code'=>1,'url'=>$qr_file]); //直接返回二唯码

        //$qr_file="upload/tg/tg_qr.jpg";
        $image = \think\Image::open($qr_file);
        //$image->thumb(240,240)->save($qr_file_thumb); //压缩图
    
        //三,拼装图片
        $image = \think\Image::open('upload/tg/tg_bak.jpg');   //背景图
        //$image->text('    扫码领福利,推广码:'.$customer['id'],$_SERVER["DOCUMENT_ROOT"].'/upload/tg/msyh.ttc',36,'#FFFFFF',8,-50,0);
        $image->water($qr_file,[250,1170]);     //参数2:水印位置,默认右下角，参数3:水印透明度0-100
        $image->save($tg_file);        //保存图片
        unlink($qr_file);
        return json(['code'=>1,'url'=>$tg_file]);//返回图片路径
        return "<image src='/".$tg_file."' />";
    }


    public function thinkQRcode($data){
        header("Content-type:image/png");
        $code = new QRcode();
        $code->png($data,false,'L',4)->text('请扫码付款',20,['center',740],'#ff4351');
        $imagestring = base64_encode(ob_get_contents());
        ob_end_clean(); 
        return "<img src='data:image/png;base64,{$imagestring}'  />";
            //生成二维码
            // ->logo('static/image/avatar-m.jpg')         //生成logo二维码
            // ->background(180,500)                       //给二维码加上背景
            // ->text($role,20,['center',740],'#ff4351')   //添加文字水印
            // ->text($nick_name,20,['center',780],'#000000')
            // ->getPath();
    }

    private function error($str){
        return $str;
    }

    //post提交，用此方法发起支付,curl
    function http_post($url, $header='', $data){
        $headers[] = "Accept:application/json";
        $headers[] = "Content-Type:application/json";
        $headers[] = "User-Agent:application/json";
        //$headers[] = $header;
 
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $tmpInfo = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;
    }

    //图片查看
    public function image_man(){
        $all=Request::param();

        $dir = public_path();
        //$dir="F:\code\wy_shop\public";

        if(!empty($all['path'])){
            $dir=base64_decode($all['path']);
        }

        echo "路径:【".$dir."】,是否目录:".is_dir($dir)."<br/>";


        if (is_dir($dir)){
            if ($dh = opendir($dir)){

                while (($file = readdir($dh)) !== false){
                    $full_file = realpath($file);

                    if(is_dir($file)) {
                        echo "<a href='/imagex/image_man/path/".base64_encode(realpath($file))."'>".$file."</a>";
                        //echo "<a href='/imagex/image_man/path/".$file."'>".$file."</a>";
                        //echo ", is a directory";
                    }
                    if(is_file($file)) {
                        echo $file;
                        //echo ", is a file";
                    }
                    echo $file.":".is_dir($file).",".is_file($file).",";
                    echo "<br>";
                                        
                }
        
            closedir($dh);
            }
        }
  


    }


    public function isImage($filename){
        $types = '.gif|.jpeg|.png|.bmp'; //定义检查的图片类型

        $info = @getimagesize($filename);
        //getimagesize() 函数将测定任何 GIF，JPG，PNG，SWF，SWC，PSD，TIFF，BMP，IFF，JP2，JPX，JB2，JPC，XBM 或 WBMP 图像文件的大小并返回图像的尺寸以及文件类型及图片高度与宽度。
        // Array(
        //     [0] => 290
        //     [1] => 69
        //     [2] => 3
        //     [3] => width="290" height="69"
        //     [bits] => 8
        //     [mime] => image/png
        // )
        // 返回结果说明

        // 索引 0 给出的是图像宽度的像素值
        // 索引 1 给出的是图像高度的像素值
        // 索引 2 给出的是图像的类型，返回的是数字，其中1 = GIF，2 = JPG，3 = PNG，4 = SWF，5 = PSD，6 = BMP，7 = TIFF(intel byte order)，8 = TIFF(motorola byte order)，9 = JPC，10 = JP2，11 = JPX，12 = JB2，13 = SWC，14 = IFF，15 = WBMP，16 = XBM        

        if(is_array($info)) return $info;
        return false;



    }



}
